package com.lily.aidouzixun.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;

import com.lily.aidouzixun.R;
import com.lily.aidouzixun.fragment.DynamicFragment;
import com.lily.aidouzixun.fragment.HomeFragment;
import com.lily.aidouzixun.message.MessageType;
import com.lily.aidouzixun.fragment.UserCenterFragment;
import com.lily.aidouzixun.ui.ImageTextView;
import com.lily.aidouzixun.util.L;
import com.lily.aidouzixun.util.MyConstant;
import com.lily.aidouzixun.util.T;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends FragmentActivity {
    private final static String TAG = "MainActivity";
    private static Context context;
    private Activity activity;
    private MyHandler myHandler;
    private String key = "";

    private int curId = 0;  //当前Fragment的Id
    private int lastId = -1; //上一个Fragmeng的Id

    private static final int ID_FIRST = 1;   //第一个FragmentID
    private static final int ID_SECOND = 2; //第二个FragmentID
    private static final int ID_THIRD = 3; //第三个FragmentID
    private static final int[] FRAGMENT_IDS = {ID_FIRST, ID_SECOND, ID_THIRD};   //Fragment的ID数组

    private final String TAG_FIRST = HomeFragment.class.getName(); //第一个FragmentTAG
    private final String TAG_SECOND = DynamicFragment.class.getName(); //第二个FragmentTAG
    private final String TAG_THIRD = UserCenterFragment.class.getName(); //第三个FragmentTAG
    private final String[] FRAGMENT_TAGS = {TAG_FIRST, TAG_SECOND, TAG_THIRD};  //Fragment的Tag数组

    private static Dialog updateSoftDialog;
    private ImageTextView itvFirst;  //第一个导航条
    private ImageTextView itvSecond;  //第二个导航条
    private ImageTextView itvThird; //第三个导航条
    private ImageTextView[] itvs;  //底部导航栏的ImageTextView数组

    private boolean isExit = false; //准备退出  false-没准备好；true-准备好了

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init(savedInstanceState);
        findViews();
        setListeners();
    }

    @Override
    protected void onResume() {
        try {
            super.onResume();
            //显示内容
            showContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 用于接收回传数据
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            switch (requestCode) {
                case MyConstant.IntentForResultCODE.LOGIN_REQUESTCODE:   //登录结果
                case MyConstant.IntentForResultCODE.MODIFY_AVATAR_BY_IMAGE_REQUESTCODE: //通过本地设置头像
                case MyConstant.IntentForResultCODE.MODIFY_AVATAR_BY_CAMERA_REQUESTCODE: //通过拍照设置头像
                case MyConstant.IntentForResultCODE.PHOTO_ZOOM_REQUESTCODE: //图片裁剪
                    FragmentManager fragmentManager = getSupportFragmentManager();
                    Fragment userCenterFragment = fragmentManager.findFragmentByTag(TAG_THIRD);
                    userCenterFragment.onActivityResult(requestCode, resultCode, data);
                    break;
                case MyConstant.IntentForResultCODE.PUBLISH_DISCUSS_REQUESTCODE:    //发布动态
                    FragmentManager discussFragmentManager = getSupportFragmentManager();
                    Fragment discussFragment = discussFragmentManager.findFragmentByTag(TAG_SECOND);
                    discussFragment.onActivityResult(requestCode, resultCode, data);
                    break;
                default:
                    break;
            }
            super.onActivityResult(requestCode, resultCode, data);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 初始化信息
     * @param savedInstanceState
     */
    private void init(Bundle savedInstanceState) {
        this.key = this.hashCode() + "";
        if(context == null) {
            context = MainActivity.this;
        }
        if(activity == null) {
            activity = MainActivity.this;
        }
        //现场恢复：如果有现场保护，则取出保存的Fragment标志，否则这是当前Fragment为第一个
        if(savedInstanceState != null) {
            curId = savedInstanceState.getInt("mainWhich");
        } else {
            curId = ID_FIRST;
        }
        myHandler = new MyHandler(activity);  //初始化Handler
    }

    /**
     * 找到得到视图上的控件
     */
    private void findViews() {
        //BottomBar上的控件
        itvFirst = (ImageTextView)this.findViewById(R.id.main_home);
        itvSecond = (ImageTextView)this.findViewById(R.id.main_history);
        itvThird = (ImageTextView)this.findViewById(R.id.main_shopping);
        itvs = new ImageTextView[]{itvFirst, itvSecond, itvThird};
        //设置图片下面的标题单行显示，超出部分，后面显示...
        itvFirst.setSingleLine();
        itvSecond.setSingleLine();
        itvThird.setSingleLine();
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //第一个导航条
        itvFirst.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (curId == ID_FIRST) {
                    return;
                }
                lastId = -1;
                curId = ID_FIRST;
                showContent();
            }
        });

        //第二个导航条
        itvSecond.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (curId == ID_SECOND) {
                    return;
                }
                curId = ID_SECOND;
                showContent();
            }
        });

        //第三个导航条
        itvThird.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (curId == ID_THIRD) {
                    return;
                }
                curId = ID_THIRD;
                showContent();
            }
        });

    }

    /**
     * 显示内容
     */
    private void showContent() {
        if(lastId == curId) {
            return;
        }
        lastId = curId; //记录下当前页
        showFragment();
        showBottomTab();
    }


    /**
     * 显示Fragment
     */
    public void showFragment() {
        for(int i = 0; i < FRAGMENT_IDS.length; i++) {
            if(curId == FRAGMENT_IDS[i]) {
                selectFragment(FRAGMENT_TAGS[i]);
            } else {
                unselectFragment(FRAGMENT_TAGS[i]);
            }
        }
    }

    /**
     * 选择tag对应的Fragment
     * @param tag
     */
    public void selectFragment(String tag) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragment = fragmentManager.findFragmentByTag(tag);
        if (fragment == null) {
            fragment = Fragment.instantiate(context, tag);
            fragmentTransaction.add(R.id.main_content, fragment, tag);
            fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        } else {
            if (fragment.isDetached()) {
                fragmentTransaction.attach(fragment);
            } else {
                fragmentTransaction.show(fragment);
            }
        }
        fragmentTransaction.commitAllowingStateLoss();
    }

    /**
     * 不选择tag对应的Fragmnet
     * @param tag
     */
    private void unselectFragment(String tag) {
        try {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            Fragment fragment = fragmentManager.findFragmentByTag(tag); //得到tag对应Fragment
            if (fragment != null) {
                if(fragment.isVisible()) {
                    fragmentTransaction.hide(fragment);
                }
            }
            fragmentTransaction.commitAllowingStateLoss();
        } catch (Exception e) {
            L.e(TAG, "hideFragment fail!");
        }
    }

    /**
     * 显示底部导航栏样式
     */
    public void showBottomTab() {
        for (int i = 0; i < itvs.length; i++) {
            ImageTextView test = itvs[i];
            if(curId == FRAGMENT_IDS[i]) {
                itvs[i].setITSelected(true);
            } else {
                itvs[i].setITSelected(false);
            }
        }
    }

    /**
     * 连续点击两次退出
     */
    private void exitBy2Click() {
        if (isExit) {   //准备好了（即连续点击了两次），直接退出
            finish();
        } else {
            isExit = true;  //准备退出
            T.shortToast(context, "再按一次就退出！");
            Timer tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        }
    }
    /**
     * 回退，连续点击两次退出
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            exitBy2Click();
        }
        return false;
    }

    /**
     * 自定义的Handler
     */
    static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        /**
         * 构造方法，传递Activity对象，防止内存泄露
         * @param mActivity
         */
        MyHandler(Activity mActivity) {
            mActivityReference = new WeakReference<Activity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final Activity activity = mActivityReference.get();
                if(activity !=  null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:   //显示对话框
                            break;
                        case MessageType.CLOSE_DIALOG:  //关闭对话框
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED: //请求数据完成
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
